<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * author	:	Tran Van Thanh
 * email	:	thanhtran@vietnambiz.com
 * date		:	07/09/2011
 */

require_once 'client'.EXT;

class Reviews extends Client {

	function __construct()
	{
		parent::__construct();		
        $this->load->library(array("form_validation","Message","pagination"));
		$this->load->helper(array('custom_string','form','text'));
		$this->load->helper('admin/upload');
		$this->load->model(array('reviews_model','home_model','questions_model'));	

		$this->data['support'] 	= $this->home_model->get_support();
		
		$this->data['products_best_sales']	= $this->home_model->get_all_products('best_sales',5);
		
		$this->data['questions_usually']	= $this->questions_model->get_questions_usually();
	}
	
	function index($page = 1)
	{			
		$limit		=	8;		
		
		$offset     = 	($page-1)*$limit;
			
		$result		=	$this->reviews_model->get_all_reviews($limit,$offset);

		$num_rows   =	$result['num_rows'];
		
		$rows		=	$result['rows'];
		
		$total		=	ceil($num_rows/$limit);			
		
		$url		=	base_url().'khach-hang-noi-ve-chung-toi';		
			
		$conf = array(
			'cur_page'			=>	$page,
			'base_url'			=>	$url,
			'total_rows'		=>	$total,
			'cur_page'			=>	$page,			
			'cur_class'			=>	'currentpage',
			'prev_class'		=>	'prevnext',
			'next_class'		=>	'prevnext',
			'next_link'			=>	'Tiếp theo',
			'prev_link'			=>	'Trang trước',
			'show_total'		=>	'no',
			'show_first_last'	=>	'no'
		);
		
		$this->pagination->initialize($conf);
		$this->data['pagnav'] 		= $this->pagination->non_ajax();
		$this->data['page']			= $page;
		$this->data['num_rows'] 	= $num_rows;
		$this->data['total_page'] 	= $total;
		
		$this->data['reviews']			= $rows;	
		
		//meta tag
	    $this->data['title'] 			= get_title('[TITLE]',"Khách hàng nói về chúng tôi");
	    $this->data['description'] 		= get_description('[DESCRIPTION]',"Khách hàng nói về chúng tôi");
		$this->data['keywords'] 		= get_keywords('[KEYWORDS]',"Khách hàng nói về chúng tôi");	    
		//end meta tag
				
		$this->data['tpl_file']		=	'reviews/index';
		$this->load->view('layout/default',$this->data);
	}
	
	function send_notes()	
	{
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {        	      	  
        	$this->form_validation->set_message('required', '%s');
            $this->form_validation->set_message('valid_email', '%s');
            $this->form_validation->set_rules("txtName","Họ tên","required");            
            $this->form_validation->set_rules("txtPosition","Chức vụ","required");
            $this->form_validation->set_rules("txtCompany","Công ty","required");
            $this->form_validation->set_rules("txtAddress","Địa chỉ","required");
            $this->form_validation->set_rules("txtEmail","Email","required|valid_email");
            $this->form_validation->set_rules("txtPhone","Điện thoại","required");
            $this->form_validation->set_rules("txtContent","Nội dung","required");
                                  
            if($this->form_validation->run() === TRUE)
            {         
            	 $fullname			=	$this->input->post('txtName');
				 $position			=	$this->input->post('txtPosition');
				 $address			=	$this->input->post('txtAddress');            	                  
            	 $email          	=	$this->input->post('txtEmail');
                 $phone				=	$this->input->post('txtPhone');  
                 $company			= 	strip_tags($this->input->post('txtCompany'));               
                 $content           = 	$this->input->post('txtContent');
                 $id_customer		=  	0;
                 
                 if(strtolower($this->input->post('val')) == strtolower($this->session->userdata('security_code')))
				 {				 	
	                 /* Insert into tables customers*/
	                 if($this->questions_model->check_email_customers($email)==FALSE)
	                 {	                 	
	                 	// Upload images	            		
	            		$album_dir = 'uploads/logo/';
	            		
	            		if(!is_dir($album_dir))
	            		{	            			
	            			create_dir($album_dir);	            			
	            		}	   
		               
		                $ext = get_ext($_FILES["logo"]["name"]);
	                    if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
	                    	continue;
	                    }
	                    if($_FILES['logo']['error'] === 0) 
            	    	{            	    	
				        	$new_path = $album_dir.$_FILES["logo"]["name"];
				        	move_uploaded_file($_FILES["logo"]['tmp_name'], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);
            	    	}                    
	                    
				        $data_customers = array(
		                 	'fullname'		=> strip_tags($fullname),		                 	
		                 	'email'			=> strip_tags($email),
		                 	'address'		=> $address,
		                 	'telephone'		=> strip_tags($phone),
		                 	'position'		=> strip_tags($position),
		                 	'logo'			=> $this->_create_thumb_logo($new_path),
		                 	'date_create'	=> date('Y-m-d H:i:s'),
		                 	'active'		=> 'yes'
	                 	);
	                 	$this->db->insert('customers', $data_customers);
		             	$id_customer = $this->db->insert_id();            				            			            				              
	                 }
	                 else
	                 {
	                 	$customer_info = $this->questions_model->get_customers_info_by_email($email);
		                $id_customer   = $customer_info->id;  
	                 }
	                 
	                 //Insert to table contact with type = reviews	                
	                  $data = array(
	                  	'id_customer'		=> $id_customer,
	                  	'company'			=> $company,	                  	                 
	                  	'contents'			=> $content,
	                  	'date_create'		=> date('Y-m-d H:i:s')	                  	                 
	                  );
	                  $re = $this->db->insert('reviews', $data);
	                  if($re == TRUE)
	                  {
	                 	$this->message->add("success",'<li class=success><p>Bạn đã gửi ý kiến thành công! Xin cảm ơn!<META HTTP-EQUIV=refresh CONTENT=5;URL="'.base_url().'khach-hang-noi-ve-chung-toi'.'"></p></li>');
	                  }       
		                 
				 }
				 else
				 {
				 	$this->message->add("error",'<li class=error><p>Mã xác nhận không đúng!</p></li>');
				 }             	
            }
        }
		//meta tag
	    $this->data['title'] 			= get_title('[TITLE]',"Gửi ý kiến");
	    $this->data['description'] 		= get_description('[DESCRIPTION]',"Gửi ý kiến");
		$this->data['keywords'] 		= get_keywords('[KEYWORDS]',"Gửi ý kiến");	    
		//end meta tag
		
		$this->data['tpl_file']		=	'reviews/send_notes';
		$this->load->view('layout/default',$this->data);
	}
	
	function captcha()
  	{
    	$this->load->helper('date');
      	$this->load->library('captcha_image');
      	$config=array(
        	'height'  		=>  '248',
        	'width'   		=>  '90',
        	'num_string'    => 	5,
        	'x'    			=>  10,
        	'text_color' 	=> 	array(0,0,255)      		      		   
      	);
	    $this->captcha_image->initialize($config);
      	$this->data['img']  = $this->captcha_image->output();
      	$this->load->view('captcha',$this->data);      
  	} 
  	
	function _create_thumb_logo($img_path = '')
	{
		$sizes = config_item('thumb_logo');
		$this->load->helper('string');
		$pathinfo = pathinfo($img_path);
		$new_name = $pathinfo['basename'];
		
		if($img = $this->db->from('customers')->where('logo',$pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name)->get()->row())
		{
			$temp	=	explode('.',$pathinfo['basename']);
			$new_name	=	$temp[0].date('-his-mdy').'.'.$pathinfo['extension'];
		}

		rename($img_path, $pathinfo['dirname'].'/'.$new_name);

        include_once (config_item('phpThumb_dir')."ThumbLib.inc.php");

        $options = array(
		    'resizeUp' 		=> true,
		    'jpegQuality'	=> 88,
        );

		
		foreach($sizes as $size)
		{
			$thumb_dir  = $pathinfo['dirname'].'/thumb_'.$size;
			create_dir($thumb_dir);

			$t_size = explode('-', $size);

		    $thumb 	= PhpThumbFactory::create($pathinfo['dirname'].'/'.$new_name, $options);

		    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
		    $thumb->cropFromCenter($t_size[0], $t_size[1]);
		    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
		}
		return $pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name;
	}
}